function LessonPanel(selectPanel, lessonTable, topPanel) {
    /**
     * 是否是单选
     */
    this.singleSelect = true;

    /**
     * 顶部
     */
    this.topPanel = topPanel;

    /**
     * 后台数据
     */
    this.lessons = null;
    this.lessonTable = lessonTable;

    /**
     * 被选中的课
     */
    this.selects = {};
    this.selectPanel = selectPanel;

    /**
     * 选中的天
     */
    this.days = {};
}

LessonPanel.prototype.changeMode = function(checked) {
    this.singleSelect = checked;
};

LessonPanel.prototype.parse = function(lesson) {
    var beginTime = buildTimeStr(lesson.beginTime);
    var endTime = buildTimeStr(lesson.endTime);
    var time = beginTime + "-" + endTime;

    var title = lesson.name;

    var teachers = [];
    for ( var key in lesson.teachings) {
	teachers.push(lesson.teachings[key].teacher.name);
    }

    var cssClass = lesson.courseType.cssClass;
    var classroom = lesson.classroom.name;

    return {
	cssClass : cssClass,
	time : time,
	title : title,
	teachers : teachers,
	classroom : classroom
    };
};

/**
 * 载入一天新的课程
 */
LessonPanel.prototype.loadLesson = function(day) {
    var self = this;
    $.post("../orderlesson/doViewScheduleByDay", {
	day : day
    }, function(data) {
	if (data.success) {
	    var time = null;
	    var now = new Date();

	    var inSameDay = false;

	    self.lessons = data.lessons;

	    $("#selectable").empty();
	    $(self.lessons).each(
		    function(i) {
			var lesson = self.lessons[i].lesson;
			var count = self.lessons[i].count;
			var beginTime = lesson.beginTime;

			if (isInSameDay(now, beginTime)) {
			    inSameDay = true;
			}

			time = closestTime(now, time, beginTime);

			// 产生超链Id
			var id = [ beginTime.year, beginTime.month, beginTime.date, beginTime.hours, beginTime.minutes ].join('-');

			var obj = self.parse(lesson);

			time = closestTime(now, beginTime, time);

			var url = "../lesson/listListener.do?id=" + lesson.id;

			var html = [ '<tr id="', lesson.id, '" class="', obj.cssClass, '">', '<td><a id="', id, '"><i class="icon-ok selected"></i>', obj.time, '</a></td>', '<td><a href="', url, '" target="listListener">', obj.title,
				'</a></td>', '<td>', obj.teachers.join(','), '</td>', '<td>', obj.classroom, '</td>', , '<td>', count, '</td>', '</tr>' ];

			var tr = $(html.join(''));
			tr.data("index", i);
			tr.dblclick(function() {
			    var index = $(this).data("index");
			    self.addLesson(index);
			});
			$("#selectable").append(tr);
		    });

	    if (inSameDay) {
		var id = [ time.year, time.month, time.date, time.hours, time.minutes ].join('-');

		var top = $("#" + id).offset().top;
		var height = self.topPanel.height();
		var scrollTop = top - 60 - height;

		$("html,body").animate({
		    scrollTop : scrollTop
		}, "fast");

	    } else {
		window.scroll(0, 0);
	    }
	}
    });
};

/**
 * 添加课程
 */
LessonPanel.prototype.addLesson = function(index) {
    // 单选则清空
    if (this.singleSelect) {
	this.selectPanel.empty();
	this.days = {};
	this.selects = {};
    }
    // 当前选中的课程
    var lesson = this.lessons[index].lesson;

    // 是否已存在
    var isIn = false;
    for ( var key in this.selects) {
	if (key == lesson.id && this.selects[key]) {
	    isIn = true;
	    break;
	}
    }

    if (isIn) {
	return;
    }

    var day = (lesson.beginTime.year + 1900) + "年" + (lesson.beginTime.month + 1) + "月" + lesson.beginTime.date + "日";

    var ul = null;
    for ( var key in this.days) {
	if (key == day && this.days[key]) {
	    ul = this.days[key];
	    break;
	}
    }
    if (!ul) {
	var d = $('<dt>' + day + '</dt><dd><ul class="unstyled"></ul></dd>');
	ul = d.find("ul");

	this.selectPanel.append(d);
	this.days[day] = ul;
    }

    var obj = this.parse(lesson);

    var li = $([ '<li>', '<span class="label label-info">', obj.time, '</span>', ' <strong>', obj.title, '</strong> <span class="text-success">', obj.teachers.join(','), '</span> ', obj.classroom, '</li>' ].join(''));

    var self = this;
    li.dblclick(function() {
	var day = $(this).data("day");
	var lessonId = $(this).data("id");

	self.selects[lessonId] = null;

	var parent = $(this).parent();
	var length = parent.find("li").length;
	if (length <= 1) {
	    self.days[day] = null;

	    var dd = parent.closest("dd");
	    var dt = dd.prev("dt");
	    dt.remove();
	    dd.remove();
	} else {
	    $(this).remove();
	}

	var height = self.topPanel.height();
	self.lessonTable.css("margin-top", height + "px");
    });

    li.data("id", lesson.id);
    li.data("day", day);
    this.selects[lesson.id] = li;
    ul.append(li);

    var height = this.topPanel.height();
    this.lessonTable.css("margin-top", height + "px");
};

/**
 * 清除课程
 */
LessonPanel.prototype.clearLesson = function() {
    this.selectPanel.empty();
    this.days = {};
    this.selects = {};

    var height = this.topPanel.height();
    this.lessonTable.css("margin-top", height + "px");
};

/**
 * 获得选中的课程
 */
LessonPanel.prototype.getSelectedLesson = function() {
    var lessons = this.selects;
    var lessonIds = [];
    for ( var key in lessons) {
	if (lessons[key]) {
	    lessonIds.push(key);
	}
    }

    return lessonIds;
};

/**
 * 刷新课程
 */
LessonPanel.prototype.refreshLesson = function(lessonId) {
    var url = "../orderlesson/refreshLesson";
    var self = this;
    $.post(url, {
	lessonId : lessonId
    }, function(data) {
	var tds = self.lessonTable.find("#" + lessonId).find("td");
	var lesson = data.lesson;
	var count = data.count;

	var obj = self.parse(lesson);

	tds.eq(0).html(obj.time);
	tds.eq(1).find("a").html(obj.title);
	tds.eq(2).html(obj.teachers);
	tds.eq(3).html(obj.classroom);
	tds.eq(4).html(count);
    });
};

$(function() {
    $("#studentList").selectable();

    var lessonPanel = new LessonPanel($("#lessons"), $("#lessonsTable"), $("#lessonPanel"));

    $("#btnClear").click(function() {
	lessonPanel.clearLesson();
    });

    $("#cbSingle").prop("checked", true);

    $("#cbSingle").click(function() {
	lessonPanel.changeMode($(this).prop("checked"));
    });

    $("#btn-submit").click(
	    function() {
		var lessonIds = lessonPanel.getSelectedLesson();

		if (lessonIds.length == 0) {
		    helper.warn({
			title : '提示',
			content : '还没有任何课程被选中。'
		    });

		    return false;
		}

		var signCourse = null;
		if ($("#studentList tr").length == 1) {
		    // 只有一行
		    signCourse = $("#studentList tr").data("signCourseId");
		} else {
		    // 当前选中行
		    var trs = $("tr.ui-selected");
		    if (trs.length > 0) {
			signCourse = $(trs[0]).data("signCourseId");
		    }
		}

		if (!signCourse) {
		    helper.warn({
			title : '提示',
			content : '需要选择一条学员注册课程记录。'
		    });

		    return false;
		}

		$.post("../front/doOrderLesson", {
		    lessonIds : lessonIds.join(","),
		    signCourseId : signCourse
		}, function(data) {
		    if (data.success) {
			$(data.logs).each(
				function(i) {
				    lessonPanel.refreshLesson(this.lesson.id);

				    var log = data.logs[i];

				    var label = log.timeout ? '<span class="label label-warning">补订</span>' : '<span class="label label-success">正常</span>';

				    var cardId = log.signCourse.cardId ? '(' + log.signCourse.cardId + ')' : "";

				    var html = '<div class="alert alert-success"><button class="close" type="button" data-dismiss="alert">×</button>' + label + '<div><div>' + log.student.name + '(' + log.student.stuId + ')</div><div>'
					    + log.signCourse.course.name + cardId + '</div><div><button class="cancel btn pull-right">撤销</button>' + log.lesson.name + '</div></div>';
				    var htmlEle = $(html);

				    htmlEle.find(".close").click(function() {
					var alertDiv = $(this).closest("div.alert");
					alertDiv.fadeOut(function() {
					    alertDiv.remove();
					});
				    });

				    htmlEle.data("id", log.id);

				    htmlEle.find(".cancel").click(function() {
					var alertDiv = $(this).closest("div.alert");
					var id = alertDiv.data("id");
					helper.confirm({
					    title : '确认',
					    content : '你确认要撤销该调订课记录吗？',
					    okHandler : function() {
						var url = "../orderlesson/doCancelOrderLesson";
						$.post(url, {
						    id : id
						}, function(data) {
						    if (data.success) {
							lessonPanel.refreshLesson(data.lessonId);
							alertDiv.fadeOut(function() {
							    alertDiv.remove();
							});
						    }
						});
					    }
					});
				    });

				    $("#logs").prepend(htmlEle);
				});
		    } else {
			helper.error({
			    title : '订课失败',
			    content : data.msg
			});
		    }
		});
	    });

    $("#searchText").change(function() {
	if ($(this).val().length < 2) {
	    $("#studentList").empty();
	    return;
	}
	$.post("../student/searchStudent", $("#searchForm").serialize(), function(data) {
	    if (data.success) {
		$("#studentList").empty();

		var studentHeader = true;
		$(data.students).each(function(i) {
		    var student = data.students[i];

		    var url = "viewStudentDetails?id=" + student.id;
		    var nameObj = $('<td><a href="' + url + '">' + student.name + '</a></td>');
		    var stuIdObj = $('<td>' + student.stuId + '</td>');
		    var courseTd = '<td>无注册课程</td>';

		    var length = student.courses.length;
		    if (length == 0) {
			var trObj = $("<tr></tr>").append(nameObj).append(stuIdObj).append(courseTd);
			$("#studentList").append(trObj);

			return true;
		    }

		    for ( var i = 0; i < length; i++) {
			var course = student.courses[i];

			if (studentHeader) {
			    nameObj.attr("rowspan", student.courses.length);
			    stuIdObj.attr("rowspan", student.courses.length);
			    studentHeader = false;
			} else {
			    nameObj = null;
			    stuIdObj = null;
			}

			var signUrl = "viewSignCourseDetails.jsp?id=" + student.id;

			courseTd = '<td><a href="' + signUrl + '">' + course.course.name + '</a></td>';

			var trObj = $("<tr></tr>").append(nameObj).append(stuIdObj).append(courseTd);
			trObj.data("signCourseId", course.id);
			trObj.data("studentId", student.id);

			trObj.find("a").popover({
			    placement : "bottom",
			    trigger : "hover",
			    content : 'TODO',
			    /*
			     * content : function() { var self = this;
			     * setTimeout(function() {
			     * $(self).next("div.popover").load($(self).attr("href")); },
			     * 1000); },
			     */
			    title : "注册课程详情"
			});

			$("#studentList").append(trObj);
		    }

		    studentHeader = true;
		});
	    }
	});
    });

    $("#datepicker").datepicker({
	showWeek : true,
	firstDay : 1,
	dateFormat : 'yy-mm-dd',
	showOtherMonths : true,
	selectOtherMonths : true,
	onSelect : function(dateText) {
	    lessonPanel.loadLesson(dateText);
	}
    });

    lessonPanel.loadLesson();
});

function buildTimeStr(time) {
    var hourStr = time.hours > 9 ? time.hours : "0" + time.hours;
    var minutesStr = time.minutes > 9 ? time.minutes : "0" + time.minutes;

    var str = hourStr + ":" + minutesStr;

    return str;
}

function isInSameDay(time, time1) {
    var year = time.getYear();
    var month = time.getMonth();
    var date = time.getDate();

    if (year != time1.year) {
	return false;
    }
    if (month != time1.month) {
	return false;
    }
    if (date != time1.date) {
	return false;
    }

    return true;
}

function closestTime(time, time1, time2) {
    if (!time1) {
	return time2;
    } else if (!time2) {
	return time1;
    }

    var hourSpan1 = Math.abs(time1.hours - time.getHours());
    var hourSpan2 = Math.abs(time2.hours - time.getHours());

    if (hourSpan1 == hourSpan2) {
	var minuteSpan1 = Math.abs(time1.minutes - time.getMinutes());
	var minuteSpan2 = Math.abs(time2.minutes - time.getMinutes());

	if (minuteSpan1 < minuteSpan2) {
	    return time1;
	} else {
	    return time2;
	}
    }

    if (hourSpan1 < hourSpan2) {
	return time1;
    } else {
	return time2;
    }
}
